/**
 * WidgetEventPagingInput module
 */

import React,{Component} from "react";
import { connect } from 'dva';
import classnames from 'classnames';
import { bindActionCreators } from 'redux';
import widgetsActions from '../../../actions/Editor/widgets';
import editorActions from '../../../actions/Editor/editor';
import timelinesActions from '../../../actions/Editor/timelines';
import consts from '../../../consts/consts';
import TimelineHelper from "../../../utils/TimelineHelper";
import tool from "../../../utils/tool";

class WidgetEventTrigger extends Component{
    constructor(props) {
        super(props);
        this.state = {             
            showToggle: false
        };
    }
    componentWillMount(){
        const {widget} = this.props;
        this.disabled = consts.WIDGET_TYPE_NO_EDITABLE_TYPES.indexOf(widget.type) != -1;
    }
    handleOnSelectTimeline(timelineID, widgetID, e){
        const {widgets,widget:triggerWidget} = this.props;
        let timeline = this.getTimelineById(timelineID, widgetID);
        let timelineWidget = tool.getSpecifyWidgetById(widgets,timeline.widget_id);
        if (timeline){
            timeline.triggered_by = [];
            timeline.selected = !timeline.selected;
            if (timeline.selected){
                var trigger_color = triggerWidget.action.trigger_color = (triggerWidget.action.trigger_color || TimelineHelper.getTriggerColor());

                timeline.triggered_by.push(triggerWidget.id);
                timeline.trigger_color = trigger_color;

                this.updateWidget(triggerWidget);
            } else {
                timeline.triggered_by.splice(timeline.triggered_by.indexOf(triggerWidget.id), 1);
                timeline.trigger_color = "#b5bbc7";
            }

            this.updateSelectedTimeline(timeline, widgetID);
            this.setState({
                timelines: this.timelines
            });
        }
    }
    updateSelectedTimeline(timeline, widgetID){
//        dataProvider.updateTimelineFromWidget(widgetID, timeline);
//        var timelines = dataProvider.timelines[widgetID];
//        dataProvider.updateAllTimelines(widgetID, timelines, function (_timelines){
//            var root = this.props.root;
//            root.updateTimelines(_timelines);
//        }.bind(this));
        const {updateTimeline} = this.props;
        updateTimeline(timeline);
    }
    getTimelineById(timelineID, widgetID){
//        let timelines = this.props.timelines[widgetID];
        const {timelines} = this.props;
        let result = timelines.filter(function (timeline){
            return timeline.id === timelineID;
        });
        return result[0];
    }
    getTimelineByWidgetId(widget_id){
        var timelines = this.timelines;
        var result = timelines.filter(function (timeline){
            return timeline.widget_id == widget_id;
        });
        return result[0];
    }
    handleOnToggleShowTriggerList(e){
        e.preventDefault();
        e.stopPropagation();
        this.setState({
            showToggle: !this.state.showToggle
        });
    }
    filterTimeline(_timeline,triggered_by,timelineWidget,triggerWidget){
          if (timelineWidget){
              const {widgets} = this.props;
              if (triggered_by.length){
                  if (triggered_by.indexOf(triggerWidget.id) != -1){
                      _timeline.selected = true;
                      return _timeline;
                  }
                  for(let i in triggered_by){
                      let id = triggered_by[i];
                      let _timelineWidget = tool.getSpecifyWidgetById(widgets,id);
                      if(!_timelineWidget) return _timeline;
                  }
                  return null;
              }
              return _timeline;
          }
    }
    rebuildTimelines(){
        const {widget,timelines,widgets,parent,fromTemplate} = this.props;
        let triggerWidget = !fromTemplate ? widget : parent;//parent 为模板
        let filterTimelines = [];
        for (let widgetId in timelines){
            let _timeline = timelines[widgetId];
            let timelineWidget = tool.getSpecifyWidgetById(widgets,_timeline.widget_id);
            let triggered_by = _timeline.triggered_by || [];
            _timeline.label = timelineWidget.label;
            _timeline.icon_class = timelineWidget.icon_class;
            _timeline.display = _timeline.an_types[0].an_type_display;
            let _filterTimeline = this.filterTimeline(_timeline,triggered_by,timelineWidget,triggerWidget);
            _filterTimeline && (filterTimelines.push(_filterTimeline));
        }
        return filterTimelines;
    }
    updateWidget(widget){
        const {updateWidget,setState} = this.props;
        setState({selectedWidget: widget});
        updateWidget(widget);
    }
    render(){
        const {widget,widgets} = this.props;
        let showTipNode = "";
        this.timelines = this.rebuildTimelines();
//      this.timelines = TimelineHelper.filterTimelines(dataProvider, timelines, widget);
        if (this.timelines.length){
            showTipNode = <span>{$._('Choose animation list')}</span>
        } else {
            this.disabled = true;
            showTipNode = <span>{$._('Has no animation list')}</span>
        }
        let self = this;
        return (
            <div>
                <button onClick={(e) => this.handleOnToggleShowTriggerList(e)} disabled={this.disabled} type="button" style={{display: widget.type == 3 ? "none" : "inline-block"}} className={"choose_list " + (this.disabled ? "disabled" : "")}>
                    {showTipNode}
                </button>
                <div data-trigger data-form="form">
                    <div className="trigger-container" style={{display:(this.state.showToggle ? "block" : "none")}}>
                        <div className="trigger-title">{$._('Optional material list')}</div>
                        <div className="trigger-list">
                        {
                            this.timelines.map(function (timeline){

                                return (
                                    <div key={timeline.id} onClick={(e) => this.handleOnSelectTimeline(timeline.id, timeline.widget_id,e)} className="trigger-item">
                                        <div className="trigger-item-list">
                                            <div className={"checked " + (timeline.selected ? "icon-uniF52F" : "icon-uniF471")}></div>
                                            <div className="trigger-title">{timeline.label}</div>
                                            <div className="trigger-antypes">
                                                <span className="trigger-antype-item">
                                                    <span>{timeline.start_time}</span>
                                                    <span>-</span>
                                                    <span>{timeline.end_time}</span>
                                                    <span>s</span>
                                                    <span>{timeline.display}</span>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                )
                            }.bind(this))
                        }
                        </div>
                        <div onClick={(e) => this.handleOnToggleShowTriggerList(e)} className='trigger-btn'>{$._("Confirm")}</div>
                    </div>
                    <div className="selected-item">
                    {
                        this.timelines.map(function (timeline){
                            let triggeredColor = tool.getTriggerColorByTimeline(widgets,timeline)|| timeline.trigger_color;
                            let timelineInnderNode = "";
                            if (timeline.selected){
                                timelineInnderNode =
                                    <div className="anilit">
                                        <div className="trigger-icon" style={{ background: triggeredColor }}></div>
                                        <div className="trigger-title">{timeline.label}</div>
                                        <div className="trigger-antypes">
                                            <span className="trigger-antype-item">
                                                <span>{timeline.start_time}</span>
                                                <span>-</span>
                                                <span>{timeline.end_time}</span>
                                                <span>s</span>
                                                <span>{timeline.display}</span>
                                            </span>
                                        </div>
                                    </div>
                            }
                            return (
                                <div key={timeline.id} className="trigger-item">
                                    {timelineInnderNode}
                                </div>
                            )
                        })
                    }
                    </div>
                </div>
            </div>
        )
    } 
}

const mapStateToProps = ({ editor, widgets ,timelines}) => {
  const pageId = editor.selectedPageId;
  return {
      fromTemplate: editor.fromTemplate,
      widget: editor.selectedWidget,
      widgets: widgets.filter(w => w.page_id === pageId),
      timelines: timelines.filter(t => t.page_id === pageId),
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...widgetsActions,...editorActions,...timelinesActions}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(WidgetEventTrigger);
